//
//  JSTUserDataViewController.m
//  KYKJPackDemo
//
//  Created by 01 on 17/6/1.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTUserDataViewController.h"
#import "JSTUserIconCell.h"
#import "JSTUserNickCell.h"
#import "JSTUserSexCell.h"
#import "JSTUserBirthdayCell.h"
#import "JSTSignatureCell.h"
@interface JSTUserDataViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, UITextViewDelegate, JSTPickViewDelegate>

@property (nonatomic, strong) UITableView *tabView;

@property (nonatomic, strong) JSTUserPublicModel *userModel;

@property (nonatomic, strong) UIImage *selectIconImage;

@property (nonatomic, strong) NSString *nickName;

@property (nonatomic, strong) NSString *sex;

@property (nonatomic, strong) NSString *birth_month;

@property (nonatomic, strong) NSString *birth_day;

@property (nonatomic, strong) NSString *signStr;

@property (nonatomic, strong) UITextField *nickTextFd;

@property (nonatomic, strong) UITextField *sexTextFd;

@property (nonatomic, strong) UITextField *birthDayTextFd;

@property (nonatomic, strong) UITextView *signTextView;

@property (nonatomic, assign) CGFloat maxX;

@property (nonatomic, assign) CGFloat maxY;

@property (nonatomic, strong) JSTPickerView *sexAlertView;

@property (nonatomic, strong) JSTPickerView *birthDayAlertView;

@end

@implementation JSTUserDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.userInteractionEnabled = YES;
    
    [self createCrrentUserData];
    
    [self createContent];
    
    CGSize size = [NSString sizeWithString:@"个性签名:" font:kSystemFont(kCurrentScreenWidth(12)) CGsize:CGSizeMake(kDeviceWidth, MAXFLOAT)];
    _maxX = size.width + EvaluationCellInset;
    _maxY = kCurrentScreenWidth(45);
//    [self addTap];
}

- (void)createCrrentUserData
{
    _userModel = [[JSTUserPublicModel alloc] init];
    _userModel.iconUrl = [[JSTSystemInfo userDict] valueForKey:@"icon"];
    _userModel.nickName = [[JSTSystemInfo userDict] valueForKey:@"name"];
    _userModel.sex = [[JSTSystemInfo userDict] valueForKey:@"sex"];
    _userModel.birthDay = [NSString stringWithFormat:@"%@", [[JSTSystemInfo userDict] valueForKey:@"birth_month"]];
    _userModel.signature = [[JSTSystemInfo userDict] valueForKey:@"sign"];
}

- (void)createContent
{
    [self.view addSubview:self.tabView];
    
    UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(0, 0, 75, 44);
    [submitBtn setTitle:@"提 交" forState:UIControlStateNormal];
    [submitBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(submitUserInfo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *submitItem = [[UIBarButtonItem alloc] initWithCustomView:submitBtn];
    self.navigationItem.rightBarButtonItem = submitItem;
}


#pragma mark - tabeleView数据源&代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 1;
    }else
    {
        return 4;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10.;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1.;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return kCurrentScreenWidth(70);
    }else
    {
        if (indexPath.row < 3)
        {
            return kCurrentScreenWidth(45);
        }else
        {
            return kCurrentScreenWidth(50) + EvaluationCellInset*2;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JSTUserIconCell         *iconCell;
    JSTUserNickCell         *nickCell;
    JSTUserSexCell          *sexCell;
    JSTUserBirthdayCell     *birthdayCell;
    JSTSignatureCell        *signatureCell;
    if (indexPath.section == 0)
    {
        iconCell = [tableView dequeueReusableCellWithIdentifier:@"userIconCell"];
        if (!iconCell)
        {
            iconCell = [[JSTUserIconCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userIconCell"];
        }
        iconCell.selectionStyle = UITableViewCellSelectionStyleNone;
        iconCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (_selectIconImage)
        {
            iconCell.iconImage = _selectIconImage;
        }
        [iconCell createContent:_userModel.iconUrl];
        
        return iconCell;
    }else
    {
        if (indexPath.row == 0)
        {
            nickCell = [tableView dequeueReusableCellWithIdentifier:@"userNickCell"];
            if (!nickCell)
            {
                nickCell = [[JSTUserNickCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userNickCell"];
            }
            nickCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [nickCell addSubview:self.nickTextFd];
            
            return nickCell;
        }else if (indexPath.row == 1)
        {
            sexCell = [tableView dequeueReusableCellWithIdentifier:@"userSexCell"];
            if (!sexCell)
            {
                sexCell = [[JSTUserSexCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userSexCell"];
            }
            sexCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [sexCell addSubview:self.sexTextFd];
            
            return sexCell;
        }else if (indexPath.row == 2)
        {
            birthdayCell = [tableView dequeueReusableCellWithIdentifier:@"userBirthdayCell"];
            if (!birthdayCell)
            {
                birthdayCell = [[JSTUserBirthdayCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"userBirthdayCell"];
            }
            birthdayCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [birthdayCell addSubview:self.birthDayTextFd];
            
            return birthdayCell;
        }else
        {
            signatureCell = [tableView dequeueReusableCellWithIdentifier:@"signatureCell"];
            if (!signatureCell)
            {
                signatureCell = [[JSTSignatureCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"signatureCell"];
            }
            signatureCell.selectionStyle = UITableViewCellSelectionStyleNone;
            [signatureCell addSubview:self.signTextView];
            
            return signatureCell;
        }
    }
    return nil;
}

//cell 分割线到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        [self infoTap];
    }
}

- (void)infoTap
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    actionSheet.tag = 250;
    [actionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 250)
    {
        NSUInteger sourceType = 0;
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            switch (buttonIndex)
            {
                    case 0:
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                    case 1:
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                    case 2:
                    return;
            }
        }
        else
        {
            if (buttonIndex == 2)
            {
                return;
            }
            else
            {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{}];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *pickerImage = [info objectForKey:UIImagePickerControllerEditedImage];
    _selectIconImage = pickerImage;
    
    [self.tabView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void) submitUserInfo
{
    [self refreshUserInfo];
    
    if (IsStrEmpty(_nickTextFd.text))
    {
        [self presentSheet:@"昵称不能为空哦！！！"];
        return;
    }
    NSMutableArray *imgData = [NSMutableArray array];
    if (_selectIconImage)
    {
        [imgData addObject:_selectIconImage];
    }
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:self.nickTextFd.text forKey:@"name"];
    [dict setValue:self.sexTextFd.text forKey:@"sex"];
    [dict setValue:self.birthDayTextFd.text forKey:@"birth_month"];
    [dict setValue:self.signTextView.text forKey:@"sign"];
    [JSTNewServer requestEditUserInfo:dict getImageData:imgData success:^(NSDictionary *dataDic)
    {
        NSMutableDictionary *userDict = [NSMutableDictionary dictionary];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"birth_day"]] forKey:@"birth_day"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"birth_month"]] forKey:@"birth_month"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"icon"]] forKey:@"icon"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"ma"]] forKey:@"ma"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"name"]] forKey:@"name"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"sex"]] forKey:@"sex"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"sign"]] forKey:@"sign"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"taobao_key"]] forKey:@"taobao_key"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"taobao_secret"]] forKey:@"taobao_secret"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"token"]] forKey:@"token"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"username"]] forKey:@"username"];
        [userDict setValue:[JSTSystemInfo getStr:[dataDic valueForKey:@"uid"]] forKey:@"uid"];
        
        DLog(@"------- userDict = %@", userDict);
        // user信息持久化
        [JSTSystemInfo cacheUserDict:userDict];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSString *errStr)
    {
        [self presentSheet:errStr];
    }];
}

- (void) refreshUserInfo
{
    NSIndexPath *nickIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    NSIndexPath *sexIndexPath = [NSIndexPath indexPathForRow:1 inSection:1];
    NSIndexPath *birthDayIndexPath = [NSIndexPath indexPathForRow:2 inSection:1];
    NSIndexPath *signIndexPath = [NSIndexPath indexPathForRow:3 inSection:1];
    
    JSTUserNickCell *nickCell = (JSTUserNickCell *)[self tableView:self.tabView cellForRowAtIndexPath:nickIndexPath];
    _nickName = nickCell.textFd.text;
    
    JSTUserSexCell *sexCell = (JSTUserSexCell *)[self tableView:self.tabView cellForRowAtIndexPath:sexIndexPath];
    _sex = sexCell.textFd.text;
    
    JSTUserBirthdayCell *birthDayCell = (JSTUserBirthdayCell *)[self tableView:self.tabView cellForRowAtIndexPath:birthDayIndexPath];
    _birth_month = birthDayCell.textFd.text;
    
    JSTSignatureCell *signCell = (JSTSignatureCell *)[self tableView:self.tabView cellForRowAtIndexPath:signIndexPath];
    _signStr = signCell.textView.text;
    
    DLog(@"-------- nickName = %@", _nickName);
    DLog(@"-------- sex = %@", _sex);
    DLog(@"-------- birthDay = %@", _birth_month);
    DLog(@"-------- signStr = %@", _signStr);
}

- (void) eitdNickName:(UITextField *)textFd
{
    if (textFd.text.length >= 8)
    {
        textFd.text = [textFd.text substringToIndex:8];
    }
}

- (void) showSexSelect
{
    [self.view endEditing:YES];
    [self.sexAlertView showOnWindow];
}

- (void) showBirthdaySelect
{
    [self.view endEditing:YES];
    [self.birthDayAlertView showOnWindow];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length >= 50)
    {
        textView.text = [textView.text substringToIndex:50];
        [self presentSheet:@"字数不能超过50个字！"];
    }
}

- (void)confirmBtnHaveClick:(JSTPickerView *)pickView resultString:(NSString *)resultString indexPath:(NSIndexPath *)indexPath
{
    if (pickView == self.sexAlertView)
    {
        self.sexTextFd.text = resultString;
    }
    else if (pickView == self.birthDayAlertView)
    {
        self.birthDayTextFd.text = resultString;
    }
    [pickView dismissView];
}

- (UITableView *)tabView
{
    if (!_tabView)
    {
        _tabView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tabView.delegate = self;
        _tabView.dataSource = self;
    }
    return _tabView;
}

- (UITextField *)nickTextFd
{
    if (!_nickTextFd)
    {
        _nickTextFd = [[UITextField alloc] initWithFrame:CGRectMake(_maxX, 0, kDeviceWidth - _maxX - EvaluationCellInset, _maxY)];
        _nickTextFd.placeholder = @"请填写";
        _nickTextFd.font = kSystemFont(kCurrentScreenWidth(12));
        [_nickTextFd addTarget:self action:@selector(eitdNickName:) forControlEvents:UIControlEventEditingChanged];
        _nickTextFd.text = _userModel.nickName;
    }
    return _nickTextFd;
}

- (UITextField *)sexTextFd
{
    if (!_sexTextFd)
    {
        _sexTextFd = [[UITextField alloc] initWithFrame:CGRectMake(_maxX, 0, kDeviceWidth - _maxX - EvaluationCellInset, _maxY)];
        _sexTextFd.placeholder = @"请选择";
        _sexTextFd.font = kSystemFont(kCurrentScreenWidth(12));
        _sexTextFd.text = _userModel.sex;
        
        UIButton *selectBtn = [[UIButton alloc] initWithFrame:_sexTextFd.bounds];
        selectBtn.backgroundColor = kClearColor;
        [selectBtn addTarget:self action:@selector(showSexSelect) forControlEvents:UIControlEventTouchUpInside];
        [_sexTextFd addSubview:selectBtn];
    }
    return _sexTextFd;
}

- (UITextField *)birthDayTextFd
{
    if (!_birthDayTextFd)
    {
        _birthDayTextFd = [[UITextField alloc] initWithFrame:CGRectMake(_maxX, 0, kDeviceWidth - _maxX - EvaluationCellInset, _maxY)];
        _birthDayTextFd.placeholder = @"请选择";
        _birthDayTextFd.font = kSystemFont(kCurrentScreenWidth(12));
        _birthDayTextFd.text = _userModel.birthDay;
        
        UIButton *selectBtn = [[UIButton alloc] initWithFrame:_sexTextFd.bounds];
        selectBtn.backgroundColor = kClearColor;
        [selectBtn addTarget:self action:@selector(showBirthdaySelect) forControlEvents:UIControlEventTouchUpInside];
        [_birthDayTextFd addSubview:selectBtn];
    }
    return _birthDayTextFd;
}

- (UITextView *)signTextView
{
    if (!_signTextView)
    {
        _signTextView = [[UITextView alloc] initWithFrame:CGRectMake(_maxX, 0, kDeviceWidth - _maxX - EvaluationCellInset, kCurrentScreenWidth(50))];
        _signTextView.delegate = self;
        _signTextView.text = _userModel.signature;
    }
    return _signTextView;
}

- (JSTPickerView *)sexAlertView
{
    if (!_sexAlertView)
    {
        _sexAlertView = [[JSTPickerView alloc] initWithFrame:kDeviceFrame string:nil getType:sexType];
        _sexAlertView.delegate = self;
    }
    return _sexAlertView;
}

- (JSTPickerView *)birthDayAlertView
{
    if (!_birthDayAlertView)
    {
        _birthDayAlertView = [[JSTPickerView alloc] initWithFrame:kDeviceFrame string:nil getType:birthdayType];
        _birthDayAlertView.delegate = self;
    }
    return _birthDayAlertView;
}
@end
